package login;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
/**
 * This is the core of registering the user.  Checks form data, and
 * adds it to the database if correct.
 * @author Ben
 */
public class RegisterDAO {
    static Connection currentCon = null;
    //rs and rsNum are later used as result sets a.k.a. what's left over after executing a query with a statement
    static ResultSet rs = null;
    static int rsNum = 0; 
    
        /**
	 * This method is the entire purpose of the class - adding a user to the database.
         * First, checks to see if all the fields are appropriately filled out.
         *  -sets possible empty fields appropriately
         *  -connects to database and searches for preexisting username
         *  -checks all the form data
         * If no checks fail it uses the previously established connection to add the users data.
         * 
         * @param user 
         * @return User the user that was submitted. It will have the "registrationStatus" string
         * changed to the respected error or success.  This string is evaluated in RegisterServlet
         * to decide the appropriate screen to show.
         */
    public static User register(User user) {
        //Dealing with possible empty form fields
        Statement stmt = null;
        
        if(user.getUsername()==null || (user.getUsername().length()<1 || user.getUsername().length()>25)){
            user.setRegistrationStatus("Username must be between 1 and 25 characters");
            return user;
        }
        user.setUsername(user.getUsername().replaceAll("'", "''"));
        String username = user.getUsername();
        if(user.getInterests()==null  || user.getInterests().equals("")  || user.getInterests().equals("Enter your interests here...")){
            user.setInterests("I have no interests");
        }
        if(user.getStreet2()==null){
            user.setStreet2("");
        }
        username.replaceAll("'", "''");
        //setting up appropriate queries. Search query checks for existing username, and insertQuery is used at the end to add the user if form was correctly filled out.
        String searchQuery = "select * from users where uname='" + username + "'";
        try {
            //This part sets up connection to the database, so the queries can be used
            currentCon = ConnectionManager.getConnection();
            stmt = currentCon.createStatement();
            rs = stmt.executeQuery(searchQuery);
            boolean userExists = rs.next();
            
            //all the checks
            if (userExists){
                user.setRegistrationStatus("Username already used");
                return user;
            }
            if(user.getPassword()==null || (user.getPassword().length()<1 || user.getPassword().length()>25)){
                user.setRegistrationStatus("Password must be between 1 and 25 characters");
                return user;
            }
            if(user.getFirstName()==null || (user.getFirstName().length()<1 || user.getFirstName().length()>25)){
                user.setRegistrationStatus("First name must be between 1 and 25 characters");
                return user;
            }
            if(user.getLastName()==null || (user.getLastName().length()<1 || user.getLastName().length()>25)){
                user.setRegistrationStatus("Last name must be between 1 and 25 characters");
                return user;
            }
            if((user.getEmail()==null || (user.getEmail().length()<1) || user.getLastName().length()>100 || !user.getEmail().matches("[A-Za-z][\\w\\.\\-]*@[A-Za-z][\\w\\-]*\\.(com|org|net)"))){
                user.setRegistrationStatus("Invalid email");
                return user;
            }
            if(user.getClimateZone() == null){
                user.setRegistrationStatus("Error with climate zone");
                return user;
            }
            if(user.getStreet1() == null || user.getCity() == null || user.getState() == null || user.getZip()==null){
                user.setRegistrationStatus("Empty Mailing Address Input");
                return user;
            }else{
                if(!user.getStreet1().matches("\\d{1,5}[ ]*[\\w \\.\\-']+") || user.getStreet1().length()>200){
                    user.setRegistrationStatus("Invalid Street Address for line 1");
                    return user;
                }
                if(!user.getCity().matches("[\\w \\.\\-']+") || user.getCity().length()>100){
                    user.setRegistrationStatus("Invalid city entry, must be 1 to 100 characters");
                    return user;
                }
                if(!user.getState().matches("[A-Z]{2}")){
                    user.setRegistrationStatus("Invalid state entry, must be 2 upercase characters");
                    return user;
                }
                if(!user.getZip().matches("\\d{5}")){
                    user.setRegistrationStatus("Invalid zipcode, must be 5 digits");
                    return user;
                }
                if(user.getStreet2().length()>200){
                    user.setRegistrationStatus("Invalid street address 2");
                    return user;
                }
                if(user.getInterests().length()>500){
                    user.setRegistrationStatus("Interests field must be less than 500 characters");
                    return user;
                }
            }
            user.setPassword(user.getPassword().replaceAll("'", "''"));
            user.setFirstName(user.getFirstName().replaceAll("'", "''"));
            user.setLastName(user.getLastName().replaceAll("'", "''"));
            user.setEmail(user.getEmail().replaceAll("'", "''"));
            user.setStreet1(user.getStreet1().replaceAll("'", "''"));
            user.setStreet2(user.getStreet2().replaceAll("'", "''"));
            user.setState(user.getState().replaceAll("'", "''"));
            user.setZip(user.getZip().replaceAll("'", "''"));
            user.setInterests(user.getInterests().replaceAll("'", "''"));
            user.setCity(user.getCity().replaceAll("'", "''"));
            
            
             String insertQuery = "INSERT INTO users(uname,password,firstName,lastName,email,climateZone,street1,street2,city,stateMail,zip,interests,isAdmin,isLocked,consecutiveFails) "
                +  "VALUES('"+username+"','"+user.getPassword()+"','"+user.getFirstName()+"','"+user.getLastName()+"','"+user.getEmail()+"','"+user.getClimateZone()+"','"+user.getStreet1()+"','"+user.getStreet2()+"','"+user.getCity()+"','"+user.getState()+"','"+user.getZip()+"','"+user.getInterests()+"',false,false,0)";
        
            //once all the checks passed they are added to the database.
            stmt=currentCon.createStatement();
            rsNum = stmt.executeUpdate(insertQuery);
        } catch (Exception ex) {
            System.out.println("connection bad-probably database url" + ex);
        }
        
        user.setValid(true);
        return user;
    }
}
